package service

import (
	"apitestAfterGo/dao"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"github.com/zhuxiujia/GoMybatis"
)

type userService struct {
	userMapper               *domain.UserMapper
	UserDetailsMapper        *domain.UserDetailsMapper
	Login                    func(username string) (domain.User, error)          `tx:"" rollback:"error"`
	Register                 func(arg domain.User) (int64, error)                `tx:"" rollback:"error"`
	DeleteUser               func(id int) (int64, error)                         `tx:"" rollback:"error"`
	GetUserById              func(id int) (domain.User, error)                   `tx:"" rollback:"error"`
	GetAllUserByPage         func(dto dto.SearchInputDto) ([]domain.User, error) `tx:"" rollback:"error"`
	CountUsers               func(value string) (int, error)                     `tx:"" rollback:"error"`
	GetUserByUserName        func(username string) (domain.User, error)          `tx:"" rollback:"error"`
	ChangeStatus             func(status domain.User) (int64, error)             `tx:"" rollback:"error"`
	UpdatePasswordByUsername func(arg domain.User) (int64, error)                `tx:"" rollback:"error"`
	GetAllUser               func() ([]domain.User, error)                       `tx:"" rollback:"error"`
}

var UserServiceImpl userService

func init() {
	UserServiceImpl = userService{
		userMapper:        &dao.UserMapper,
		UserDetailsMapper: &dao.UserDetailsMapper,
		Login: func(username string) (domain.User, error) {
			return UserServiceImpl.userMapper.SelectTemplate(username)
		},
		Register: func(arg domain.User) (int64, error) {
			user, err := UserServiceImpl.userMapper.InsertByUser(arg)
			userName, _ := UserServiceImpl.userMapper.GetUserByUserName(arg.Username)
			_ = UserServiceImpl.UserDetailsMapper.InsertByUserDetail(userName.Id)
			return user, err
		},
		DeleteUser: func(id int) (int64, error) {
			return UserServiceImpl.userMapper.DeleteTemplate(id)
		},
		GetUserById: func(id int) (domain.User, error) {
			return UserServiceImpl.userMapper.GetUserById(id)
		},
		GetAllUserByPage: func(dto dto.SearchInputDto) ([]domain.User, error) {
			dto.Current = (dto.Current - 1) * dto.PageSize
			return UserServiceImpl.userMapper.GetAllUserByPage(dto)
		},
		CountUsers: func(value string) (int, error) {
			return UserServiceImpl.userMapper.CountUsers(value)
		},
		GetUserByUserName: func(username string) (domain.User, error) {
			return UserServiceImpl.userMapper.GetUserByUserName(username)
		},
		ChangeStatus: func(status domain.User) (int64, error) {
			return UserServiceImpl.userMapper.ChangeStatus(status)
		},
		UpdatePasswordByUsername: func(arg domain.User) (int64, error) {
			return UserServiceImpl.userMapper.UpdatePasswordByUsername(arg)
		},
		GetAllUser: func() ([]domain.User, error) {
			return UserServiceImpl.userMapper.GetAllUser()
		},
	}
	GoMybatis.AopProxyService(&UserServiceImpl, &dao.Engine)
}
